package com.jianan.mis.sys;

import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.PlatformUI;
import org.eclipse.update.configuration.IConfiguredSite;
import org.eclipse.update.configuration.ILocalSite;
import org.eclipse.update.core.IFeature;
import org.eclipse.update.core.IFeatureReference;
import org.eclipse.update.core.SiteManager;
import org.eclipse.update.operations.IInstallFeatureOperation;
import org.eclipse.update.operations.OperationsManager;
import org.eclipse.update.search.BackLevelFilter;
import org.eclipse.update.search.EnvironmentFilter;
import org.eclipse.update.search.IUpdateSearchCategory;
import org.eclipse.update.search.IUpdateSearchResultCollector;
import org.eclipse.update.search.UpdateSearchRequest;
import org.eclipse.update.search.UpdateSearchScope;

public class UpdateAction extends Action {
	
	public final static String ID = "com.jianan.mis.app.sys.update";

	public UpdateAction() {
		setId(ID);
		setActionDefinitionId(ID);
		setText("在线升级(&U)");
		setToolTipText("在线升级系统");
		setImageDescriptor(ImageManager
				.getImageDescriptor(IImageKeys.UPDATE_SOFTWARE));
	}
	
	// 待升级内容列表
	private List<IInstallFeatureOperation> updateOperation = new ArrayList<IInstallFeatureOperation>();

	// 升级是否成功的标志
	private int updateTag = -1;

	public void run() {
		ProgressMonitorDialog pmd = new ProgressMonitorDialog(null);
		IRunnableWithProgress rwp = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor)
					throws InvocationTargetException, InterruptedException {
				monitor.beginTask("正在进行系统升级...", IProgressMonitor.UNKNOWN);
				try {
					// 获得升级URL
					final String homeBase = "http://localhost:8080/com.jianan.mis.update/";
					monitor.subTask("搜索服务器站点" + homeBase + "...");
					searchUpdateInfo(homeBase, monitor);
					// 执行升级信息
					updateTag = installUpdate(updateOperation, monitor);
					monitor.done();
				} catch (CoreException ce) {
					ce.printStackTrace();
				} catch (MalformedURLException me) {
					me.printStackTrace();
				}
			}
		};
		try {
			pmd.run(true, false, rwp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (updateTag == 1)
			PlatformUI.getWorkbench().restart();
		else if (updateTag == 0)
			MessageDialog.openInformation(null, IMessageKeys.INFORMATION,
					"服务器站点没有可供升级的新版本!");
		else
			MessageDialog.openError(null, IMessageKeys.INFORMATION, "升级失败!");
	}

	// 搜索升级信息
	private void searchUpdateInfo(String homeBase, IProgressMonitor monitor)
			throws MalformedURLException, OperationCanceledException,
			CoreException {
		// 准备搜索
		IUpdateSearchCategory category = UpdateSearchRequest
				.createDefaultSiteSearchCategory();
		UpdateSearchScope searchScope = new UpdateSearchScope();
		URL url = new URL(homeBase);
		searchScope.addSearchSite(homeBase, url, null);
		UpdateSearchRequest searchRequest = new UpdateSearchRequest(category,
				searchScope);
		// 过滤掉升级站点的较低版本内容
		searchRequest.addFilter(new BackLevelFilter());
		// 过滤掉与当前环境不匹配的
		searchRequest.addFilter(new EnvironmentFilter());
		// 设置搜索相关信息
		IUpdateSearchResultCollector collector = new SearchResultCollector();
		searchRequest.performSearch(collector, monitor);
	}

	@SuppressWarnings("deprecation")
	private int installUpdate(List<IInstallFeatureOperation> update,
			IProgressMonitor monitor) throws CoreException {
		if (update.size() > 0) {
			monitor.subTask("获取本地系统信息...");
			// 获得本地站点
			ILocalSite localSite = SiteManager.getLocalSite();
			// 获取本地配置信息
			IConfiguredSite localConfigSite = localSite
					.getCurrentConfiguration().getConfiguredSites()[0];
			IFeatureReference[] localFeatures = localConfigSite
					.getConfiguredFeatures();
			for (int i = 0; i < update.size(); i++) {
				// 当前更新操作
				IInstallFeatureOperation op = (IInstallFeatureOperation)
					update.get(i);
				// 得到功能部件
				IFeature feature = op.getFeature();
				for (int j = 0; j < localFeatures.length; j++) {
					String id = localFeatures[j].getVersionedIdentifier().getIdentifier();
					String sid = feature.getVersionedIdentifier().getIdentifier();
					// 本地功能部件ID号与更新服务器的功能部件ID号相等
					if (sid.equals(id)) {
						// 版本号大于本地功能部件的版本号
						if (feature.getVersionedIdentifier().getVersion()
								.isGreaterThan(localFeatures[j]
								.getVersionedIdentifier().getVersion())) {
							// 安装升级部件
							localConfigSite.install(feature, null, monitor);
							// 返回升级成功标志
							return 1;
						}
					}
				}
			}
		}
		return 0;
	}

	// 收集更新内容
	class SearchResultCollector implements IUpdateSearchResultCollector {
		public void accept(IFeature match) {
			IInstallFeatureOperation oper = OperationsManager
					.getOperationFactory().createInstallOperation(null, match,
							null, null, null);
			updateOperation.add(oper);
		}
	}

}
